import useGameDataStore from '@/store/gameData'
import { canRemove } from '@/utils'
import { defineComponent, onMounted, ref } from 'vue'
import Card from './Card'

export interface GameMapRef {
  initGame: () => void
  shuffer: () => void
}

export default defineComponent({
  name: 'GameMap',
  emits: ['remove'],
  setup() {
    const isLoading = ref(true)
    const gameDataStore = useGameDataStore()
    const { initGame, moveMainAreaCard } = gameDataStore

    const onCardClick = (
      type: number,
      level: number,
      row: number,
      col: number,
      removeable: boolean
    ) => {
      if (!removeable) return
      moveMainAreaCard(type, level, row, col)
    }

    onMounted(() => {
      initGame()
      isLoading.value = false
    })
    /* render 函数 */
    return () => {
      const { mainAreaCards } = gameDataStore
      const levels = mainAreaCards.map((level, levelIndex) => {
        return level.map((row, rowIndex) => {
          return row.map((col, colIndex) => {
            if (col === 0) return null
            const removeable = canRemove(
              mainAreaCards,
              levelIndex,
              rowIndex,
              colIndex
            )
            const style = {
              top: `${rowIndex * 2}rem`,
              left: `${colIndex * 2}rem`,
              zIndex: levelIndex
            }
            const type = mainAreaCards[levelIndex][rowIndex][colIndex]
            return (
              <>
                <div
                  class="absolute"
                  style={style}
                  onClick={() => {
                    onCardClick(
                      type,
                      levelIndex,
                      rowIndex,
                      colIndex,
                      removeable
                    )
                  }}>
                  <Card name={type} />
                </div>
                {removeable ? null : (
                  <div
                    class="w-16 h-16 absolute bg-gray-400 bg-opacity-50"
                    style={style}></div>
                )}
              </>
            )
          })
        })
      })
      return <div class="m-2 h-96 relative">{!isLoading.value && levels}</div>
    }
  }
})
